package org.jeecgframework.web.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.ValidForm;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.DataUtils;
import org.jeecgframework.core.util.ExceptionUtil;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.CbsServiceCapacityServiceI;
import org.jeecgframework.web.system.pojo.base.CbsServiceCapacityEntity;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.ZyInspectionPlanEntity;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;



/**   
 * @Title: Controller
 * @Description: 服务商产能
 * @author onlineGenerator
 * @date 2016-10-12 10:43:05
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/cbsServiceCapacityController")
public class CbsServiceCapacityController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CbsServiceCapacityController.class);

	@Autowired
	private CbsServiceCapacityServiceI cbsServiceCapacityService;
	@Autowired
	private SystemService systemService;
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 服务商产能列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "cbsServiceCapacity")
	public ModelAndView cbsServiceCapacity(HttpServletRequest request) {
		List<TSDepart> departList = systemService.findHql("from TSDepart where orgType = ?", StaticValue.DIC_ORG_TYPE_THIRD_PARTY);
		request.setAttribute("thirdDepartList", departList);
		return new ModelAndView("com/zybk/cbsservicecapacity/cbsServiceCapacityList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	@ResponseBody
	public void datagrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid,String year,String serviceProvider) {
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT");
		sb.append(" 	SUM(min_capacity) as minCount,");
		sb.append(" 	SUM(plan_capacity) as planCount,");
		sb.append(" 	SUM(max_capacity) as maxCount,");
		sb.append(" 	service_provider as serviceProvider,");
		sb.append(" 	YEAR (years) as year");
		sb.append(" FROM");
		sb.append(" 	cbs_service_capacity where 1 = 1");
		if(StringUtil.isNotEmpty(year)){
			sb.append(" and year(years) = " +year );
		}
		if(StringUtil.isNotEmpty(serviceProvider)){
			sb.append(" and service_provider = '"+serviceProvider+"'");
		}
		sb.append(" GROUP BY");
		sb.append(" 	service_provider,");
		sb.append(" 	YEAR (years)");
		sb.append(" order by service_provider,YEAR (years) desc");
		List<Map<String, Object>> resultList = systemService.findForJdbc(sb.toString(), dataGrid.getPage(), dataGrid.getRows());
		List<Map<String, Object>> totalList = systemService.findForJdbc(sb.toString());
		dataGrid.setTotal(totalList.size());
		dataGrid.setResults(resultList);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 服务商产能新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(CbsServiceCapacityEntity cbsServiceCapacity, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(cbsServiceCapacity.getId())) {
			cbsServiceCapacity = cbsServiceCapacityService.getEntity(CbsServiceCapacityEntity.class, cbsServiceCapacity.getId());
			req.setAttribute("cbsServiceCapacityPage", cbsServiceCapacity);
		}
		List<TSDepart> departList = systemService.findHql("from TSDepart where orgType = ?", StaticValue.DIC_ORG_TYPE_THIRD_PARTY);
		req.setAttribute("thirdDepartList", departList);
		req.setAttribute("year", DataUtils.getYear() + 1);
		return new ModelAndView("com/zybk/cbsservicecapacity/cbsServiceCapacity-add");
	}
	
	/**
	 * 添加时验证所选年度和服务商是否存在
	 * @param serviceId
	 * @param year
	 * @return
	 */
	@RequestMapping(params="validServiceYear")
	@ResponseBody
	public int validServiceYear(String serviceId,String year){
		try {
			List<CbsServiceCapacityEntity> capacityList = systemService.findHql("from CbsServiceCapacityEntity where serviceProviderDepart.id = ? and year(years) = ?", serviceId,Integer.parseInt(year));
			return capacityList.size();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 1;
	}
	
	/**
	 * 获取服务商在指定的年月中巡检了多少设备
	 * @param serviceId
	 * @param year
	 * @param month
	 * @param param
	 * @return
	 */
	@RequestMapping(params="getServiceProviderIpEsNum")
	@ResponseBody
	public Map<String, Object> getServiceProviderIpEsNum(String serviceId,String year,String month,String param){
		Map<String, Object> map = new HashMap<String, Object>();
		TSDepart depart = systemService.get(TSDepart.class, serviceId);
		List<ZyInspectionPlanEntity> ipList = systemService.findHql("from ZyInspectionPlanEntity where company = ? and year(actualDate) = ? and month(actualDate) = ?", depart.getOrgCode(),Integer.parseInt(year),Integer.parseInt(month));
		if(ipList.size() > Integer.parseInt(param)){
			map.put("status", ValidForm.N);
			message = "您填写的"+month+"月份数据错误,实际巡检数量为"+ipList.size();
		}else{
			map.put("status", ValidForm.Y);
		}
		map.put("info", message);
		return map;
	}
	

	/**
	 * 添加服务商产能
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(HttpServletRequest request,String minCapacityStr,String planCapacityStr,String maxCapacityStr,String serviceProvider,String year) {
		AjaxJson j = new AjaxJson();
		message = "服务商产能添加成功";
		try{
			String minCapacitys[] = minCapacityStr.split(",");
			String planCapacitys[] = planCapacityStr.split(",");
			String maxCapacitys[] = maxCapacityStr.split(",");
			for (int i = 0; i < minCapacitys.length; i++) {
				CbsServiceCapacityEntity capacity = new CbsServiceCapacityEntity();
				capacity.setMinCapacity(Integer.parseInt(minCapacitys[i]));
				capacity.setMaxCapacity(Integer.parseInt(maxCapacitys[i]));
				capacity.setPlanCapacity(Integer.parseInt(planCapacitys[i]));
				String years = year + "-" + (i+1 < 10 ? "0"+(i+1):i+1) + "-01";
				capacity.setYears(DataUtils.str2Date(years, DataUtils.date_sdf));
				TSDepart depart = systemService.get(TSDepart.class, serviceProvider);
				capacity.setServiceProviderDepart(depart);
				systemService.save(capacity);
			}
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "服务商产能添加失败";
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 服务商产能编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(HttpServletRequest req,String serviceProvider,String year) {
		List<CbsServiceCapacityEntity> capacityList = systemService.findHql("from CbsServiceCapacityEntity where serviceProviderDepart.id = ? and year(years) = ? order by years",serviceProvider,Integer.parseInt(year));
		List<TSDepart> departList = systemService.findHql("from TSDepart where orgType = ?", StaticValue.DIC_ORG_TYPE_THIRD_PARTY);
		req.setAttribute("year", year);
		req.setAttribute("serviceProvider", serviceProvider);
		req.setAttribute("dataList", capacityList);
		req.setAttribute("thirdDepartList", departList);
		return new ModelAndView("com/zybk/cbsservicecapacity/cbsServiceCapacity-update");
	}
	
	/**
	 * 更新服务商产能
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate( HttpServletRequest request,String capacityIdStr,String maxCapacityStr,String minCapacityStr,String planCapacityStr) {
		AjaxJson j = new AjaxJson();
		message = "服务商产能更新成功";
		try {
			String capacityIds[] = capacityIdStr.split(",");
			String maxCapacitys[] = maxCapacityStr.split(",");
			String minCapacitys[] = minCapacityStr.split(",");
			String planCapacitys[] = planCapacityStr.split(",");
			for (int i = 0; i < capacityIds.length; i++) {
				CbsServiceCapacityEntity capacity = systemService.get(CbsServiceCapacityEntity.class, capacityIds[i]);
				capacity.setMinCapacity(Integer.parseInt(minCapacitys[i]));
				capacity.setMaxCapacity(Integer.parseInt(maxCapacitys[i]));
				capacity.setPlanCapacity(Integer.parseInt(planCapacitys[i]));
				systemService.saveOrUpdate(capacity);
			}
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "服务商产能更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	
	/**
	 * 删除服务商产能
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(CbsServiceCapacityEntity cbsServiceCapacity, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		cbsServiceCapacity = systemService.getEntity(CbsServiceCapacityEntity.class, cbsServiceCapacity.getId());
		message = "服务商产能删除成功";
		try{
			cbsServiceCapacityService.delete(cbsServiceCapacity);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "服务商产能删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除服务商产能
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		message = "服务商产能删除成功";
		try{
			for(String id:ids.split(",")){
				CbsServiceCapacityEntity cbsServiceCapacity = systemService.getEntity(CbsServiceCapacityEntity.class, 
				id
				);
				cbsServiceCapacityService.delete(cbsServiceCapacity);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "服务商产能删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		return new ModelAndView("com/zybk/cbsservicecapacity/cbsServiceCapacityUpload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(CbsServiceCapacityEntity cbsServiceCapacity,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(CbsServiceCapacityEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, cbsServiceCapacity, request.getParameterMap());
		List<CbsServiceCapacityEntity> cbsServiceCapacitys = this.cbsServiceCapacityService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"服务商产能");
		modelMap.put(NormalExcelConstants.CLASS,CbsServiceCapacityEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("服务商产能列表", "导出人:"+ResourceUtil.getSessionUserName().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,cbsServiceCapacitys);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(CbsServiceCapacityEntity cbsServiceCapacity,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		modelMap.put(TemplateExcelConstants.FILE_NAME, "服务商产能");
		modelMap.put(TemplateExcelConstants.PARAMS,new TemplateExportParams("Excel模板地址"));
		modelMap.put(TemplateExcelConstants.MAP_DATA,null);
		modelMap.put(TemplateExcelConstants.CLASS,CbsServiceCapacityEntity.class);
		modelMap.put(TemplateExcelConstants.LIST_DATA,null);
		return TemplateExcelConstants.JEECG_TEMPLATE_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<CbsServiceCapacityEntity> listCbsServiceCapacityEntitys = ExcelImportUtil.importExcelByIs(file.getInputStream(),CbsServiceCapacityEntity.class,params);
				for (CbsServiceCapacityEntity cbsServiceCapacity : listCbsServiceCapacityEntitys) {
					cbsServiceCapacityService.save(cbsServiceCapacity);
				}
				j.setMsg("文件导入成功！");
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
}
